Ext.onReady(function() {
	Ext.SSL_SECURE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
	Ext.BLANK_IMAGE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
	// Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
	Ext.util.CSS.swapStyleSheet('theme', currentTheme);
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	var pageSize = 20;
	
	// tab页面
    var centerTabPanel = new Ext.TabPanel({
        region : 'center',
        deferredRender : false,
        activeTab : 1,
        margins : '0 5 0 0',
        id:'centerTabPanelOrg',
       // plugins : new Ext.ux.TabCloseMenu(),
        resizeTabs : false,
        minTabWidth : 50,
        //tabWidth : 230,

        enableTabScroll : true,
        autoScroll : true,
         items:[{
            title: '下级标签：',
           // tabWidth:120,
           iconCls: 'tabsDown',
          //contentEl:'grid-div',
            disabled:true
           // autoScroll:true
        },
          {
            title: '导医信息',
            iconCls: 'tabs',
             //tabWidth:150,
            contentEl:'grid-div',
            autoScroll:true
        }],
        loadPage : function(href, cls, title) {
            var tabId = 'workPanel' + cls;
            var tab = this.getComponent(tabId);
            if (tab) {
                this.setActiveTab(tab);
            } else {
                var autoLoad = {
                    url : href,
                    scripts : true
                };
                var p = this.add(new DocPanel({
                    id : tabId,
                    cclass : cls,
                    layout : 'fit',
                    items : [new IFrameComponent({
                        id : tabId,
                        url : href
                    })],
                    title : title,
                    iconCls : 'tabs'
                }));
                this.setActiveTab(p);
            }
        }
    });
    IFrameComponent = Ext.extend(Ext.BoxComponent, {
        onRender : function(ct, position) {
            this.el = ct.createChild({
                tag : 'iframe',
                id : 'iframe-' + this.id,
                frameBorder : 0,
                src : this.url
            });
        }
    });
    DocPanel = Ext.extend(Ext.Panel, {
        closable : true,
        autoScroll : true,
        initComponent : function() {
            DocPanel.superclass.initComponent.call(this);
        },
        scrollToMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                var top = (el.getOffsetsTo(this.body)[1])
                        + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {
                    duration : .75,
                    callback : this.hlMember.createDelegate(this, [member])
                });
            }
        },
        scrollToSection : function(id) {
            var el = Ext.getDom(id);
            if (el) {
                var top = (Ext.fly(el).getOffsetsTo(this.body)[1])
                        + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {
                    duration : .5,
                    callback : function() {
                        Ext.fly(el).next('h2').pause(.2).highlight('#8DB2E3', {
                            attr : 'color'
                        });
                    }
                });
            }
        },
        hlMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                el.up('tr').highlight('#cadaf9');
            }
        }
    });
	
	new Ext.Viewport({
		region : 'center',
		layout : 'fit',
		items : centerTabPanel
	});
	
	var replyFlag = new Ext.data.SimpleStore({
		fields : ['value', 'label'],
		data : [['', '全部'], ['1', '已处理'], ['2', '未处理']]
	});
	
	var isReplyQuery = new Ext.form.ComboBox({
		fieldLabel : '处理状态',
		store : replyFlag,
		hiddenName : 'replyFlag',
		displayField : 'label',
		valueField : 'value',
		typeAhead : true,
		editable : false,
		mode : 'local',
		triggerAction : 'all',
		selectOnFocus : true,
		allowBlank : true,
		width : 120,
		value:''
	});	
	
	
	var marriageStore = new Ext.data.Store({
		proxy : new Ext.data.ScriptTagProxy({
			url : '../../dataDictionary/getDictionaryWidthCode.action?&tableName=marriage'
		}),
		fields : ['value', 'label'],
		reader : new Ext.data.ArrayReader({}, [{
			name : 'value',
			type : 'string'
		}, {
			name : 'label',
			type : 'string'
		}]),
		remoteSort : false
	});
	marriageStore.load();
	function format_marriage(value) {
		var bv = '';
		for (var i = 0; i < marriageStore.getCount(); i++) {
			if (marriageStore.getAt(i).data['value'] == value) {
				bv = marriageStore.getAt(i).data['label'];
				break;
			}
		}
		return bv;
	}
	
	var educationStore = new Ext.data.Store({
		proxy : new Ext.data.ScriptTagProxy({
			url : '../../dataDictionary/getDictionaryWidthCode.action?&tableName=education'
		}),
		fields : ['value', 'label'],
		reader : new Ext.data.ArrayReader({}, [{
			name : 'value',
			type : 'string'
		}, {
			name : 'label',
			type : 'string'
		}]),
		remoteSort : false
	});
	educationStore.load();
	function format_education(value) {
		var bv = '';
		for (var i = 0; i < educationStore.getCount(); i++) {
			if (educationStore.getAt(i).data['value'] == value) {
				bv = educationStore.getAt(i).data['label'];
				break;
			}
		}
		return bv;
	}

	var queryButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/query.png",
		id : 'queryButton',
		cls : 'x-btn-text-icon',
		text : '查询',
		tooltip : '查询记录',
		handler : onQueryClick
	});

	var addButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/add.png",
		id : 'addButton',
		cls : 'x-btn-text-icon',
		text : '添加',
		tooltip : '添加一条新的记录',
		// disabled:true,
		handler : onAddClick
	});
	var modButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/edit.png",
		id : 'modButton',
		cls : 'x-btn-text-icon',
		text : '修改',
		// disabled:true,
		tooltip : '修改一条选中记录。',
		handler : onModClick
	});
	
	var delButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/del.png",
		id : 'delButton',
		cls : 'x-btn-text-icon',
		text : '删除',
		// disabled:true,
		tooltip : '删除已选中的记录。',
		handler : onDelClick
	});


	var yearArrayData = new Array();
	for (var i = 2008; i <= (new Date()).getYear() + 1; i++) {
		yearArrayData[i - 2008] = [i, i + '年'];
	}
	var yearstore = new Ext.data.SimpleStore({
		fields : [{
			name : 'value'
		}, {
			name : 'label'
		}]
	});
	yearstore.loadData(yearArrayData);
	var combo = new Ext.form.ComboBox({
		fieldLabel : '年份',
		store : yearstore,
		displayField : 'label',
		valueField : 'value',
		typeAhead : true,
		editable : false,
		mode : 'local',
		triggerAction : 'all',
		selectOnFocus : true,
		width : 100
	});
	combo.on('select', function() {
		reloadComboxWithTree();
		gridStore.proxy = new Ext.data.ScriptTagProxy({
			url : encodeURI('../../district/buildDistrict46JSONString.action?districtYear='
					+ combo.value + "&districtCode=" + comboxWithTree.value)
		});
		gridStore.reload();
	});
	if (combo.value == null)
		combo.value = curYear;
		
	 //显示操作按钮
	function createGridButton(index, value, contentid, record) {
		new Ext.Button({
			renderTo : contentid,
			text : value,
			handler : function(btn, e) {
						var ridStr = record.data['userId'];
						centerTabPanel.loadPage('../../dy/showDetail.action?memId='+ridStr, ridStr, value);
					},
			cls : 'x-btn-text',
			scope : this
		});
	}

	function renderBtn_inputDepartment(val, p, record) {
		var contentId = Ext.id();
		createGridButton.defer(1, this, [1, "查看明细", contentId, record]);
		return ('<div id="' + contentId + '"></div>');
	}

	var gridStore = new Ext.data.Store({
		proxy : new Ext.data.ScriptTagProxy({
			url : encodeURI('../../dy/query4JSONString.action')
		}),
		reader : new Ext.data.JsonReader({
			root : 'results',
			totalProperty : 'total',
			id : 'id'
		}, [
{name:'id',mapping:'id'},
{name:'address',mapping:'address'},
{name:'marriage',mapping:'marriage'},
{name:'education',mapping:'education'},
{name:'workUint',mapping:'workUint'},
{name:'post',mapping:'post'},
{name:'selfIncome',mapping:'selfIncome'},
{name:'spouse',mapping:'spouse'},
{name:'spouseBirthday',mapping:'spouseBirthday'},
{name:'spouseEducation',mapping:'spouseEducation'},
{name:'spouseUnit',mapping:'spouseUnit'},
{name:'spousePost',mapping:'spousePost'},
{name:'spouseIncome',mapping:'spouseIncome'},
{name:'FIncome',mapping:'FIncome'},
{name:'cz',mapping:'cz'},
{name:'fc',mapping:'fc'},
{name:'cc',mapping:'cc'},
{name:'jrcp',mapping:'jrcp'},
{name:'father',mapping:'father'},
{name:'fatherBirthday',mapping:'fatherBirthday'},
{name:'fatherUnit',mapping:'fatherUnit'},
{name:'fatherPost',mapping:'fatherPost'},
{name:'fatherIncome',mapping:'fatherIncome'},
{name:'mother',mapping:'mother'},
{name:'motherBirthday',mapping:'motherBirthday'},
{name:'montherUnit',mapping:'montherUnit'},
{name:'montherPost',mapping:'montherPost'},
{name:'montherIncome',mapping:'montherIncome'},
{name:'totalIncome',mapping:'totalIncome'},
{name:'child',mapping:'child'},
{name:'childMarriage',mapping:'childMarriage'},
{name:'childAge',mapping:'childAge'},
{name:'childUnit',mapping:'childUnit'},
{name:'childPost',mapping:'childPost'},
{name:'childIncome',mapping:'childIncome'},
{name:'childSex',mapping:'childSex'},
{name:'child2',mapping:'child2'},
{name:'childMarriage2',mapping:'childMarriage2'},
{name:'childAge2',mapping:'childAge2'},
{name:'childUnit2',mapping:'childUnit2'},
{name:'childPost2',mapping:'childPost2'},
{name:'childIncome2',mapping:'childIncome2'},
{name:'childSex2',mapping:'childSex2'},
{name:'userId',mapping:'userId'},
{name:'createTime',mapping:'createTime'},
{name:'isDual',mapping:'isDual'},
{name:'authorName',mapping:'authorName'}
		]),
		remoteSort : false
	});

	var sm = new Ext.grid.CheckboxSelectionModel();

	var cm = new Ext.ux.grid.LockingColumnModel([sm, {
		header : "查看明细",
		width : 80,
		align : 'center',
		sortable : false,
		locked : false,
		renderer:renderBtn_inputDepartment,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'isDual',
		header : "是否处理",
		dataIndex : 'isDual',
		align : 'center',
		width : 100,
		sortable : false,
		renderer:function(value){
			if(value == "1")
				return "<font color='green'>已处理</font>";
			else
				return "<font color='red'>未处理</font>";
		},
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	},{
		id : 'authorName',
		header : "病人姓名",
		dataIndex : 'authorName',
		width : 200,
		align : 'center',
		sortable : false,
		locked : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'address',
		header : "家庭住址",
		dataIndex : 'address',
		width : 250,
		align : 'center',
		renderer : function(value, p, record) {
			return '<div align="left">'+value+'</div>';
		},
		sortable : false,
		css : 'textAlign:"left";white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'marriage',
		header : "婚姻状况",
		dataIndex : 'marriage',
		align : 'center',
		width : 120,
		sortable : false,
		renderer: format_marriage,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'education',
		header : "学历",
		dataIndex : 'education',
		align : 'center',
		width : 100,
		sortable : false,
		renderer: format_education,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'workUint',
		header : "工作单位",
		dataIndex : 'workUint',
		align : 'center',
		width : 100,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'post',
		header : "职务",
		dataIndex : 'post',
		align : 'center',
		width : 100,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'selfIncome',
		header : "年收入额(元)",
		dataIndex : 'selfIncome',
		align : 'center',
		width : 100,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}
	]);
	
	var disName = new Ext.form.TextField({
		fieldLabel : '地区名称',
		id : 'disName',
		name : 'disName',
		width : 300,
		maxLength : 50,
		maxLengthText : "最大长度50"
	});

	// var grid = new Ext.grid.LockingGridPanel({
	var grid = new Ext.ux.grid.SSNJLOCKPAGEGrid({
		// el:'grid-div',
		id : 'grid',
		layout : 'fit',
		store : gridStore,
		loadMask : {
			msg : '正在加载数据，请稍候……'
		},
		cm : cm,
		height : gridHeight,
		sm : sm,
		viewConfig : {
			enableRowBody : false

		},
		bodyStyle : 'width:100%;',
		tbar : ['-', '处理状态：', isReplyQuery, '-', queryButton,'-', '&nbsp;&nbsp;&nbsp;&nbsp;'],
		frame : false,
		border : false,
		stripeRows : true
			// bbar:pagingToolbar
	});
	grid.render(Ext.get('grid-div'));
	gridStore.load({params:{start:0, limit:pageSize}});

	var formPanel;
	var win;
	function onAddClick(item) {
		var rid, code, name, upperId;
		var record, id, titleStr, codeValue,nameValue;
		titleStr = '增加记录'
		id = "";
		codeValue = "";
		nameValue = "";
		if (item == 'mod') {
			titleStr = '修改记录'
			var selectedCount = sm.getCount();
			if (selectedCount == 0) {
				Ext.Msg.alert('修改记录', '未选中任何一条记录，请选择要修改的记录！');
				return;
			} else if (selectedCount > 1) {
				Ext.Msg.alert('修改记录', '只能选择一条记录，不能同时选择多条记录！');
				return;
			}
			record = sm.getSelected();
			id = record.id;
			codeValue = record.data['code'];
			nameValue = record.data['name'];
		}

		code = new Ext.form.TextField({
			fieldLabel : '地区编码',
			id : 'code',
			name : 'district.code',
			width : 100,
			maxLength : 10,
			maxLengthText : "最大长度10",
			value : codeValue,
			allowBlank : true
		});

		upperId = new Ext.form.Hidden({
			name : 'district.upperId',
			value:-1
				// id:'districtId',
				// value:gridStore.getById(id).data['gbcode']
		});
		
		rid = new Ext.form.Hidden({
			name : 'district.id',
			value: id
				// id:'districtId',
				// value:gridStore.getById(id).data['gbcode']
		});
		
		name = new Ext.form.TextField({
			fieldLabel : '地区名称',
			id : 'name',
			name : 'district.name',
			width : 200,
			maxLength : 25,
			maxLengthText : "最大长度25",
			value : nameValue,
			allowBlank : true
		});
		if (formPanel != null) {
			formPanel.destroy(true);
			formPanel = null;
		}
		if (!formPanel) {
			formPanel = new Ext.FormPanel({
				labelAlign : 'right',
				labelWidth : 125,
				url : '../../district/save.action',
				frame : false,
				bodyStyle : 'padding:5px 5px 0',
				items : [rid, code, name, upperId]
			});
		}
		if (win != null) {
			win.destroy(true);
			win = null;
		}
		if (!win) {
			win = new Ext.Window({
				id : 'formWin',
				title : titleStr,
				border : false,
				width : 500,
				height : 150,
				minWidth : 200,
				maximizable : false,
				closeAction : 'hide',
				layout : 'fit',
				plain : false,
				closable : true,
				modal : false,
				bodyStyle : 'padding:5px;',
				buttonAlign : 'center',
				items : formPanel,
				buttons : [{
					handler : function() {
						if (formPanel.getForm().isValid()) {
						if(code.getValue()==''){
							Ext.Msg.alert('提示','请输入地区编码');
							return false;
						}
						if(name.getValue()==''){
							Ext.Msg.alert('提示','请输入地区名称');
							return false;
						}
							formPanel.getForm().submit({
								waitMsg : '正在处理，请稍等...',
								reset : true,
								failure : function(form, action) {
									Ext.MessageBox.hide();
									Ext.Msg.show({
										title : '错误',
										msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
												+ action.result.msg + '</span>',
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.WARNING
									});
								},
								success : function(form, action) {
									Ext.MessageBox.hide();
									Ext.Msg.show({
										title : '成功',
										msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
												+ action.result.msg + '</span>',
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.INFO
									});
									win.hide();
									gridStore.reload();
								},
								method : 'POST'
							});
						}
					},
					text : '保存'
				}, {
					handler : function() {
						win.hide();
					},
					text : '取消'
				}]
			});
		}
		win.show();
	}
	
	function onModClick(item) {
		onAddClick('mod')
	}

	function startWith(str1, str2) {
		if (str2 == null || str2 == "" || str1.length == 0
				|| str2.length > str1.length)
			return false;
		if (str1.substr(0, str2.length) == str2)
			return true;
		else
			return false;
	}

	// 停用地区
	function onStopClick(item) {
		var selectedCount = sm.getCount();
		if (selectedCount == 0) {
			Ext.Msg.alert('停用操作', '未选中要停用的地区，请选择要停用的数据！');
			return;
		} else {
			var records = sm.getSelections();
			var _ids = '';
			for (var i = 0; i < records.length; i++) {
				if (records[i].data['canDel'] == false
						&& curYear == combo.getValue()) {
					Ext.Msg.alert('停用操作', '该地区下已经设有管辖的单位不能进行停用！');
					return;
				}
			}

			Ext.Msg.confirm('停用记录', '请确定要停用该地区吗？按是将当前系统中停用该地区！', function(btn) {
				if (btn == 'yes') {
					var records = sm.getSelections();
					var _ids = '';
					for (var i = 0; i < records.length; i++) {
						_ids += records[i].id;
						// alert(records[i].data['canDel']);
						_ids += '_';
					}
					Ext.MessageBox.wait('正在处理，请稍等...');

					Ext.Ajax.request({
						url : '../../district/stopDistrict.action',
						failure : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '错误',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ action.result.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.WARNING
							});
						},
						success : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '成功',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ responseArray.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.INFO
							});
							gridStore.reload();
						},
						params : {
							deleteID : _ids,
							districtYear : combo.value
						}
					});
				}
			});
		}
	}
	function onDelClick(item) {
		var selectedCount = sm.getCount();
		if (selectedCount == 0) {
			Ext.Msg.alert('删除操作', '未选中要删除的数据，请选择要删除的数据！');
			return;
		} else {
			var records = sm.getSelections();
			var _ids = '';
			Ext.Msg.confirm('删除记录', '请确定要删除选中的数据吗？注：按是将彻底删除！', function(btn) {
				if (btn == 'yes') {
					var records = sm.getSelections();
					var _ids = '';
					for (var i = 0; i < records.length; i++) {
						_ids += records[i].id;
						_ids += '_';
					}
					Ext.MessageBox.wait('正在处理，请稍等...');
					Ext.Ajax.request({
						url : '../../dy/deleteInfo.action',
						failure : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '错误',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ responseArray.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.WARNING
							});
						},
						success : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '成功',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ responseArray.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.INFO
							});
							gridStore.reload();
						},
						params : {
							ids : _ids
						}
					});
				}
			});
		}
	}

	function onQueryClick(item) {
		gridStore.proxy = new Ext.data.ScriptTagProxy({
			url : encodeURI('../../dy/query4JSONString.action?type='
					+ isReplyQuery.getValue())
		});
		gridStore.reload({
			params : {
				start : 0,
				limit : pageSize
			}
		});
	}
})
